import * as React from 'react';
import { connect } from 'react-redux';
import { partial } from 'lodash';
import { message, Checkbox, Menu, Dropdown, Icon, Modal } from 'antd';

import { removeAttachment, updateAttachment } from 'actions/attachment';
import Rename from './Rename';

function isSelected(array: any, obj: any) {
  if (!array) {
    return false;
  }

  const matched = array.find((item: any) => {
    return item.id === obj.id;
  });

  return Boolean(matched);
}

interface SelectorProps {
  dispatch: (action: any) => any;
  handleCallback: () => void;
  onChange: (obj: any, checked: boolean) => any;
  selectedItems: any[];
  item: any;
  isCheck: boolean;
  className?: string;
  selectMax?: number;
}

interface SelectorState {
  showRenameModal: boolean;
}

class Selector extends React.Component<SelectorProps, SelectorState> {
  static defaultProps: SelectorProps = {
    dispatch: () => {},
    handleCallback: () => {},
    onChange: () => {},
    selectedItems: [],
    item: {},
    isCheck: false,
    selectMax: 0,
  };
  constructor(props: SelectorProps) {
    super(props);
    this.state = {
      showRenameModal: false,
    };
  }

  handleTrashConfirm = () => {
    Modal.confirm({
      title: '危险',
      content: '你确定要删除此附件吗',
      okText: '确定',
      cancelText: '取消',
      onOk: this.handleTrash,
    });
  };

  handleTrash = () => {
    const { dispatch, item, handleCallback } = this.props;

    dispatch(removeAttachment(item.id)).then((result: any) => {
      if (result.code) {
        message.error(result.msg);
      } else {
        message.success('附件删除成功');
        handleCallback();
      }
    });
  };

  handleShowRenameModal = () => {
    this.setState({
      showRenameModal: true,
    });
  };

  handleHideRenameModal = () => {
    this.setState({
      showRenameModal: false,
    });
  };

  handleChangeName = (name: string) => {
    const { item, dispatch, handleCallback } = this.props;
    const data = { name };

    dispatch(updateAttachment(item.id, data)).then((result: any) => {
      if (result.code) {
        message.error(result.msg);
      } else {
        message.success('附件改名成功');

        handleCallback();
        this.setState({
          showRenameModal: false,
        });
      }
    });
  };

  renderCheckBox() {
    const { selectedItems, item, selectMax } = this.props;
    const isChecked = isSelected(selectedItems, item);
    const disabled = selectMax !== 0 && selectedItems.length === selectMax && !isChecked;

    return (
      <Checkbox
        disabled={disabled}
        style={{ display: 'inline-block', overflow: 'hidden', whiteSpace: 'nowrap' }}
        checked={isChecked}
        onChange={partial(this.props.onChange, item, !isChecked)}>
        {item.name}
      </Checkbox>
    );
  }

  renderNopeName() {
    const menu = (
      <Menu>
        <Menu.Item>
          <a onClick={this.handleTrashConfirm} href="javascript: void 0;">
            <Icon type="delete" />
            删除
          </a>
        </Menu.Item>
        <Menu.Item>
          <a onClick={this.handleShowRenameModal} href="javascript: void 0;">
            <Icon type="edit" />
            重命名
          </a>
        </Menu.Item>
      </Menu>
    );

    const { item } = this.props;

    return (
      <Dropdown overlay={menu} trigger={['click']}>
        <a
          title={item.name}
          style={{
            position: 'relative',
            display: 'inline-block',
            width: '100%',
          }}
          className="ant-dropdown-link">
          <span
            style={{
              maxWidth: '90%',
              display: 'inline-block',
              whiteSpace: 'nowrap',
              overflow: 'hidden',
            }}>
            {item.name}&nbsp;&nbsp;
          </span>
          <Icon type="down" style={{ position: 'absolute', top: 7 }} />
        </a>
      </Dropdown>
    );
  }

  render() {
    const { isCheck, item, className } = this.props;
    return (
      <div
        className={`text-overflow-hidden ${className}`}
        style={{ padding: 5, background: '#efefef', overflow: 'hidden' }}>
        {isCheck ? this.renderCheckBox() : this.renderNopeName()}

        {this.state.showRenameModal && (
          <Rename
            name={item.name}
            onOk={this.handleChangeName}
            onCancel={this.handleHideRenameModal}
          />
        )}
      </div>
    );
  }
}

export default connect()(Selector);
